<template>
  <ProTable
    ref="tableRef"
    class="page-table"
    row-key="userId"
    :request="requestApi"
    :columns="columns"
    @selectedChange="selectedChange"
    :form-props="{ 'label-width': '82px' }"
    :formOtherColumns="formOtherColumns"
  >
    <template #toolbarHeader>
      <el-button type="primary" plain @click="onAdd">添加用户</el-button>
      <el-button v-if="multipleSelection.length" type="danger" plain @click="onDelete()">
        批量删除
      </el-button>
    </template>

    <!-- 表格列 -->
    <template #name="scope">
      <div class="name-slot">
        <el-avatar class="avatar" shape="square" :size="32" :src="scope.row.avatar" />
        <span>{{ scope.row.name }}</span>
      </div>
    </template>

    <template #sex="scope">
      <el-tag :type="scope.row.sex === 'man' ? 'primary' : 'danger'">
        {{ scope.row.sex === 'man' ? '男' : '女' }}
      </el-tag>
    </template>

    <template #status="scope">
      <span :class="['circle', statusMap[scope.row.status].type]"></span>
      {{ statusMap[scope.row.status].label }}
    </template>

    <template #operations="scope">
      <el-button link type="primary" @click="onEdit(scope.row)"> 编辑 </el-button>
      <el-divider direction="vertical" />
      <el-button link type="danger" @click="onDeleteByRow(scope.row)"> 删除 </el-button>
    </template>
  </ProTable>

  <AddUser v-model="addDialog" />
  <EditUser v-model="editState.dialog" :current="editState.current" />
</template>

<script setup>
import { reactive, ref, h } from 'vue'
import { getUserList } from '@/api/system'
import { ElMessage, ElMessageBox } from 'element-plus'
import AddUser from './components/add-user.vue'
import EditUser from './components/edit-user.vue'
import { ProTable } from '@/components/table/index.js'

defineOptions({
  name: 'User', //不命名组件，keep-alive的include不属性生效
})
const statusMap = {
  normal: { label: '正常', type: 'success' },
  freeze: { label: '冻结', type: 'error' },
  offline: { label: '关闭', type: 'primary' },
}
const tableRef = ref()
const addDialog = ref(false)
const editState = reactive({ dialog: false, current: null })
const multipleSelection = ref([])
const columns = ref([
  { type: 'selection', width: 55 },
  {
    prop: 'name',
    slotName: 'name',
    label: '用户名',
    'min-width': 110,
    search: {
      order: 1,
      valueType: 'el-input',
      props: {
        placeholder: '请输入用户名',
      },
    },
  },

  {
    prop: 'loginUser',
    label: '登录账号',
    'min-width': 110,
    search: {
      order: 5,
      props: {
        placeholder: '请输入登录账号',
      },
    },
  },
  {
    prop: 'phone',
    label: '手机号',
    'min-width': 120,
    search: {
      order: 3,
      props: {
        placeholder: '请输入手机号',
      },
    },
  },
  { prop: 'email', label: '邮箱', 'min-width': 160 },
  {
    slotName: 'sex',
    prop: 'sex',
    label: '性别',
    'min-width': 80,
    search: {
      order: 4,
      valueType: 'el-select',
      options: [
        { label: '男', value: 'man' },
        { label: '女', value: 'girl' },
      ],
      props: {
        placeholder: '请选择',
      },
    },
  },
  {
    slotName: 'status',
    prop: 'status',
    label: '状态',
    'min-width': 80,
    initialValue: 'normal',
    search: {
      order: 5,
      valueType: 'el-select',
      options: [
        { label: '正常', value: 'normal', type: 'success' },
        { label: '冻结', value: 'freeze', type: 'error' },
        { label: '关闭', value: 'offline', type: 'primary' },
      ],
      props: {
        placeholder: '请选择',
      },
    },
  },
  {
    prop: 'createDate',
    label: '创建时间',
    'min-width': 170,
    search: {
      order: 7,
      valueType: 'el-date-picker',
      props: {
        class: 'card-header-extra-action',
        clearable: true,
        type: 'daterange',
        'start-placeholder': '开始日期',
        'end-placeholder': '结束日期',
      },
    },
  },
  {
    slotName: 'operations',
    prop: 'operations',
    label: '操作',
    fixed: 'right',
    width: 120,
  },
])
const formOtherColumns = [
  {
    prop: 'useId',
    label: '用户ID',
    'min-width': 110,
    search: {
      order: 2,
      valueType: 'el-input',
      props: {
        placeholder: '请输入用户ID',
      },
    },
  },
]

const requestApi = async (params) => {
  try {
    const {
      data: { list, total },
      msg,
    } = await getUserList(params)
    return Promise.resolve({
      data: list,
      total,
      msg,
      success: true,
    })
  } catch (err) {
    ElMessage.error('数据请求失败!')
    throw new Error(`数据请求失败: ${err.message || err}`)
  }
}

// 表格选择更改
const selectedChange = (selection) => {
  multipleSelection.value = selection
}

const onDelete = () => {
  if (!multipleSelection.value.length) {
    return
  }
  const names = multipleSelection.value
    .map((item) => {
      return item.name
    })
    .join('，')
  ElMessageBox({
    title: '删除确定',
    message: h('p', null, [
      '您确定要删除用户 ',
      h('span', { style: 'font-weight: bold' }, names),
      ' 吗？',
    ]),
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then(() => {
    ElMessage({
      type: 'error',
      message: '抱歉，您没有该权限',
    })
  })
}

const onAdd = () => {
  addDialog.value = true
}

const onEdit = (row) => {
  editState.current = row
  editState.dialog = true
}

const onDeleteByRow = ({ name }) => {
  ElMessageBox({
    title: '删除确定',
    message: h('p', null, [
      '您确定要删除用户 ',
      h('span', { style: 'font-weight: bold' }, name),
      ' ？',
    ]),
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then(() => {
    ElMessage({
      type: 'error',
      message: '抱歉，您没有该权限',
    })
  })
}
</script>

<style scoped lang="scss">
.name-slot {
  display: flex;
  align-items: center;
  .avatar {
    margin-right: 8px;
  }
}
</style>
